﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using HappyBa.Core;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;
using LightInject;
using Mnk.Library.WpfControls.Components.CheckableTreeView;

namespace HappyBa.Pages
{
    /// <summary>
    /// Interaction logic for SearchPage.xaml
    /// </summary>
    public partial class SearchPage
    {
        private Config config;
        private IDataCache dataCache;
        private readonly ObservableCollection<Node> nodes = new ObservableCollection<Node>();
        private readonly IServiceContainer container;

        public SearchPage()
        {
            InitializeComponent();
            container = ((MainWindow)Application.Current.MainWindow).Container;
            container.GetInstance<IDataCollector>().OnDataChanged += (o, e) => SearchClick(o, null);
            DataContextChanged += (o, e) => SearchClick(o, null);
            View.ItemsSource = nodes;
        }

        private void SearchClick(object sender, RoutedEventArgs e)
        {
            if(container == null)return;
            config = container.GetInstance<Config>();
            dataCache = container.GetInstance<IDataCache>();
            if (config.Current == null) return;
            SelectionChanged(sender, null);
            var metrics = DoSearch();
            SetItems(metrics.Projects);
            sbReleases.Content = metrics.Projects.Length;
            sbUserStories.Content = metrics.UserStories.Count;
            sbTasks.Content = metrics.Tasks.Count;
            sbBugs.Content = metrics.Bugs.Count;
            var notUserStories = metrics.EstimatableEntities.Where(x => !(x is UIUserStory)).ToArray();
            sbDone.Content = notUserStories.Where(metrics.IsFinished).Count();
            sbInDevelopment.Content = notUserStories.Where(metrics.IsInProgress).Count();
            sbNotStarted.Content = notUserStories.Count(metrics.IsReadyForDevelopment);
            sbFailed.Content = notUserStories.Where(metrics.IsFailed).Count();
            sbNotResolvedImpediments.Content = metrics.Impediments.Count(x => !metrics.IsResolved(x));
        }

        private Metrics DoSearch()
        {
            return new Metrics(dataCache.Metrics.Data,
                new MetricsSearch(config.Current.Search, GetSearcher()));
        }

        private Func<UIStatebleEntityBase, bool> GetSearcher()
        {
            var str = Querry.Text.Trim();
            var search = GetFilterBySearchBy(str);
            search = GetFilterByState(search);
            search = GetFilterByType(search);
            if (HideResolvedImpediments.IsChecked == true)
            {
                var oldSearch = search;
                search = x =>
                {
                    if (!oldSearch(x)) return false;
                    var im = x as UIImpediment;
                    return im == null || !dataCache.Metrics.IsResolved(im);
                };
            }
            if (HideEmptyUserStories.IsChecked == true)
            {
                var oldSearch = search;
                search = x =>
                {
                    if (!oldSearch(x)) return false;
                    var us = x as UIUserStory;
                    return us == null || us.Bugs.Any() || us.Tasks.Any() || us.Impediments.Any();
                };
            }
            return search;
        }

        private Func<UIStatebleEntityBase, bool> GetFilterBySearchBy(string str)
        {
            if (string.IsNullOrEmpty(str)) return x => true;
            switch (FilterSearchBy.SelectedIndex)
            {
                case 0:
                    return (x => 
                        x.Id.ToString(CultureInfo.InvariantCulture).IndexOf(str, StringComparison.OrdinalIgnoreCase) != -1 ||
                        x.Name.IndexOf(str, StringComparison.OrdinalIgnoreCase) != -1 ||
                        (x.Description ?? string.Empty).IndexOf(str, StringComparison.OrdinalIgnoreCase) != -1
                        );
                case 1:
                    return (x => x.Id.ToString(CultureInfo.InvariantCulture).IndexOf(str, StringComparison.OrdinalIgnoreCase) != -1);
                case 2:
                    return (x => x.Name.IndexOf(str, StringComparison.OrdinalIgnoreCase) != -1);
                case 3:
                    return (x => (x.Description??string.Empty).IndexOf(str, StringComparison.OrdinalIgnoreCase) != -1);
                default:
                    throw new ArgumentException("Unknown search by: " + FilterSearchBy.SelectedValue);

            }
        }

        private Func<UIStatebleEntityBase, bool> GetFilterByType(Func<UIStatebleEntityBase, bool> search)
        {
            var oldSearch = search;
            switch (FilterType.SelectedIndex)
            {
                case 0:
                    break;
                case 1:
                    return x => (x is UITask) || (x is UIBug) || oldSearch(x);
                case 2:
                    return x => (x is UIUserStory) || oldSearch(x);
                case 3:
                    return x => !(x is UIBug) && ((x is UIUserStory) || oldSearch(x));
                case 4:
                    return x => !(x is UITask) && ((x is UIUserStory) || oldSearch(x));
                default:
                    throw new ArgumentException("Unknown type: " + FilterType.SelectedValue);
            }
            return search;
        }

        private Func<UIStatebleEntityBase, bool> GetFilterByState(Func<UIStatebleEntityBase, bool> search)
        {
            switch (FilterState.SelectedIndex)
            {
                case 0:
                    return search;
                case 1:
                    return x => search(x) && dataCache.Metrics.IsReadyForDevelopment(x);
                case 2:
                    return x => search(x) && dataCache.Metrics.IsInProgress(x);
                case 3:
                    return x => search(x) && dataCache.Metrics.IsFinished(x);
                case 4:
                    return x => search(x) && dataCache.Metrics.IsFailed(x);
                default:
                    throw new ArgumentException("Unknown state: " + FilterState.SelectedValue);
            }
        }

        private void SetItems(IEnumerable<UIEntityBase> items)
        {
            nodes.Clear();
            if (items != null)
            {
                foreach (var item in items)
                {
                    nodes.Add(BuildTree(item, false)); 
                }
            }
            View.Items.Refresh();
        }

        private static Node BuildTree(UIEntityBase item, bool childrensFinded, params Node[] parents)
        {
            var node = new Node { Data = new NodeEntityAdapter(item), IsExpanded = !childrensFinded };
            foreach (var parent in parents)
            {
                node.Parent.Add(parent);
            }
            var childs = node.Data.Children;
            foreach (var ch in childs)
            {
                var child = ((NodeEntityAdapter)ch).Entity;
                node.Children.Add(BuildTree(child, childrensFinded || childs.Count > 1, node));
            }
            return node;
        }

        private void SelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (View.SelectedValue == null)
            {
                InfoView.DataContext = null;
            }
            else
            {
                var entity = ((NodeEntityAdapter)((Node)View.SelectedValue).Data).Entity;
                InfoView.DataContext = entity;
            }
        }
    }
}
